//
// Created by daiyizheng on 2022/3/27.
//

#include <queue>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

//DFS 看成二叉树就可以了
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    if(root== nullptr)return nullptr;

    if(root==q || root==p)return root;

    TreeNode *left = lowestCommonAncestor(root->left, p, q);
    TreeNode *right = lowestCommonAncestor(root->right, p, q);

    if (left== nullptr) return right;
    if (right== nullptr) return left;

    return root;
}

//使用二叉搜索树的特性
TreeNode* lowestCommonAncestor1(TreeNode* root, TreeNode* p, TreeNode* q) {
    TreeNode *ancestor =root;
    while (ancestor){
        if(p->val<ancestor->val && q->val<ancestor->val){
            ancestor = ancestor->left;
        }else if(p->val>ancestor->val && q->val>ancestor->val){
            ancestor = ancestor->right;
        }else{
            break;
        }
    }
    return ancestor;
}